package org.kwisatz.proxybot;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Properties;
import java.util.Map.Entry;
import java.util.logging.Level;
import java.util.logging.Logger;


public class Main
{
	public final static Logger LOGGER=Logger.getLogger(Main.class.getName());
	public static void main(String[] args)
	{
		LOGGER.setLevel(Level.ALL);
		LOGGER.info("Proxy bot started");
		readConfigFile();
		try
		{			
			int port=Integer.parseInt(System.getProperty("proxybot.port","3128"));
			new Server(port).run();
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
	}

	private static String getDefaultCfg()
	{
		URL url=Main.class.getResource("/org/kwisatz/proxybot/Main.class");
		if("jar".equals(url.getProtocol()))
		{
			String path=url.getPath();
			int i=path.indexOf('!');
			try
			{
				File f = new File(new URI(path.substring(0, i)));
				f=new File(f.getParentFile(), "config.txt");
				if(f.exists())
					return f.getPath();
			}
			catch (URISyntaxException e)
			{
				e.printStackTrace();
			}			
		}
		return null;
	}
	
	private static void readConfigFile()
	{		
		String config=System.getProperty("proxybot.config", getDefaultCfg());
		if(config!=null)
		{
			LOGGER.info("Using configuration file: "+config);
			Properties ps = new Properties();
			try
			{
				FileInputStream fin = new FileInputStream(config);
				ps.load(fin);
                for (Entry<Object, Object> objectObjectEntry : ps.entrySet()) {
                    Entry e = objectObjectEntry;
                    String p = "proxybot." + e.getKey();
                    String v = System.getProperty(p);
                    if (v == null)
                        System.setProperty(p, e.getValue().toString());
                }
				fin.close();
			}
			catch (IOException e)
			{
				e.printStackTrace();
			}
		}
	}
}
